#-*-coding:utf-8-*-

import os, sys
import sqlite3 as sqlite
from parser import *

def htmls2db(opts):
    grade = opts["grade"]
    start = opts["start"]
    end   = opts["end"]
    term  = opts["term"]

    uid_prefix = "U%d" % grade
    dir_prefix = "kebiao%d_%d/" % (term, grade)
    
    con = sqlite.connect("kebiao%d_%d.sqlite" % (term, grade))
    con.text_factory = lambda x: unicode(x, "utf-8", "ignore")

    con.execute('create table if not exists kebiao' + str(term) +
            """ ([id] INTEGER  NOT NULL PRIMARY KEY AUTOINCREMENT,
                 [name] VARCHAR  NULL,
                 [weekday] INTEGER  NULL,
                 [start_time] INTEGER  NULL,
                 [end_time] INTEGER  NULL,
                 [from_week] INTEGER  NULL,
                 [to_week] INTEGER  NULL,
                 [building] VARCHAR  NULL,
                 [room] VARCHAR(8)  NULL,
                 [teacher] VARCHAR  NULL,
                 [uid] VARCHAR(11) NULL)
            """)
        
    for i in range(start, end+1):
        if i % 100 == 0:
            con.commit()
        i = str(i)
        uid = uid_prefix + "0"*(4-len(i)) + i
        print uid
        fp = open(dir_prefix + "%s.html" % uid)
        data = fp.read()
        fp.close()
        html2db(con, data, uid, term)

    con.commit()
    con.close()

def html2db(con, html, uid, term):
    try:
        parser = CourseParser(html)
        results = parser.parse()
    except Exception as error:
        print 'error:', error
        exit(0)
    for result in results: 
        con.execute("insert into kebiao%d" % term + " values(?,?,?,?,?,?,?,?,?,?,?)", 
                 (None, result['name'], result['weekday'], result['start_time'],
                 result['end_time'], result['from_week'], result['to_week'], 
                 result['building'], result['room'], result['teacher'], uid))

if __name__ == "__main__":
    htmls2db({
        'grade': 2010,
        'start': 15422,
        'end'  : 15431,
        'term' : 20111
    })
